﻿using JWTAuthentication.Helper;
using JWTAuthentication.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JWTAuthentication.Controllers {
    /// <summary>
    /// 授权
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    [Authorize]//启用授权验证
    public class JwtAuthController : ControllerBase {
        private readonly IJwtAuthConfig _jwtAuthSettings;

        public JwtAuthController(IJwtAuthConfig jwtAuthSettings) {
            _jwtAuthSettings = jwtAuthSettings;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="role">角色</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous] //不验证授权信息
        public IActionResult GetToken(string userName = "管理员", string role = "Admin") {
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(role)) {
                TokenModel tokenModel = new TokenModel() {
                    Uid = 1,
                    Uname = userName,
                    Gender = "男",
                    Email = "XXX@qq.com",
                    TokenType = "Web",
                    Role = role
                };

                var token = JwtHelper.IssueJWT(tokenModel);

                return Ok(token);
            }
            else {
                return BadRequest(new { message = "用户名不能为空" });
            }
        }

        /// <summary>
        /// 解析token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SerializeToken([FromBody] string token) {
            return Ok(JwtHelper.SerializeJWT(token));
        }
    }
}
